import json
from os import write
from pathlib import Path

from loguru import logger

from CloudEngine.IO.IMshReader import IMshReader
from CloudEngine.IO.StandardJsonLoader import StandardJsonLoader
from CloudEngine.core.StandardActor import StandardActor
from service.CacheSystem import check_cache, load_cache, save_cache
from service.utils.file import get_file_md5, read_file, write_file
from service.utils.get_file_local_path import get_file_local_path
from service.utils.scene_helper import release_actor_to_scene


def read_msh(service, params):
    path = params.get("path")
    entry_file = get_file_local_path(path, "msh")
    md5 = get_file_md5(entry_file)
    standard = None
    if check_cache(md5):
        standard_file_path = load_cache(md5)
        standard = json.loads(read_file(standard_file_path))
        logger.success("命中缓存")
    else:
        reader = IMshReader()
        reader.read(entry_file)
        standard = reader.standard
        tmp_path = "./tmp/cache_" + md5 + ".json"
        write_file(tmp_path, reader.to_json())
        save_cache(md5, tmp_path)
    loader = StandardJsonLoader()
    loader.parse(standard)
    ac = StandardActor(loader.poly_data)
    ac.topology = standard["blocks"]
    ac.loader = loader
    ac.set_render_type("SURFACE_WITH_EDGE")
    ac.name = Path(path).name
    service.model_add(ac)
    release_actor_to_scene(service, loader, ac)
    return ac.id
